package com.zwps.biz.domain.service.impl;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zwps.biz.api.enums.UserIdentityEnum;
import com.zwps.biz.api.enums.UserStatusEnum;
import com.zwps.biz.api.model.dto.auth.LoginErrorDTO;
import com.zwps.biz.api.model.dto.auth.PasswordCaptchaLoginAuthDTO;
import com.zwps.biz.api.model.dto.auth.PasswordLoginAuthDTO;
import com.zwps.biz.api.model.dto.auth.PhoneLoginDTO;
import com.zwps.biz.api.model.vo.auth.AuthInfoVO;
import com.zwps.biz.api.model.vo.auth.RemoteVO;
import com.zwps.biz.dal.db.dao.DeptDAO;
import com.zwps.biz.dal.db.dao.SysUserDAO;
import com.zwps.biz.dal.db.dao.UserDAO;
import com.zwps.biz.dal.db.object.SysUserDO;
import com.zwps.biz.dal.db.object.UserDO;
import com.zwps.biz.dal.redis.cache.AuthCache;
import com.zwps.biz.domain.config.NeteaseMessageService;
import com.zwps.biz.domain.config.SystemAuthConfig;
import com.zwps.biz.domain.config.properties.NeteasePhoneCodeMessageConfigProperties;
import com.zwps.biz.domain.converter.DeptConverter;
import com.zwps.biz.domain.converter.UserConverter;
import com.zwps.biz.domain.enums.LoginMissTypeEnum;
import com.zwps.biz.domain.enums.UserTypeEnum;
import com.zwps.biz.domain.exception.status.SystemExceptionStatus;
import com.zwps.biz.domain.service.AuthService;
import com.zwps.biz.domain.service.PagePermissionService;
import com.zwps.biz.domain.service.UserService;
import com.zwps.biz.domain.tool.JwtTool;
import com.zwps.biz.domain.tool.LoginCaptchaImageTool;
import com.zwps.common.api.model.vo.LoginInfoVO;
import com.zwps.common.api.model.vo.LoginUserVO;
import com.zwps.common.api.model.vo.RoleVO;
import com.zwps.common.core.exception.*;
import com.zwps.common.tool.crypto.DesTool;
import com.zwps.common.tool.crypto.Sm2Tool;
import com.zwps.common.tool.enums.EnumConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static ch.qos.logback.core.encoder.ByteArrayUtil.hexStringToByteArray;

@Service
@Slf4j
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final SystemAuthConfig authConfig;

    private final UserDAO userDAO;

    private final SysUserDAO sysUserDAO;

    private final DeptDAO deptDAO;

    private final AuthCache authCache;

    private final UserService userService;

    private final NeteaseMessageService neteaseMessageService;

    private final PagePermissionService pagePermissionService;

    private final NeteasePhoneCodeMessageConfigProperties neteasePhoneCodeMessageConfig;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Value("${application.auth.big-data-name}")
    private String authBigDataName;

    @Value("${application.auth.big-data-host}")
    private String authBigDataHost;

    @Value("${application.auth.big-data-pwd}")
    private String authBigDataPwd;

    @Value("${application.auth.big-data-time}")
    private long authBigDataTime;

    @Value("${application.auth.remote-host}")
    private String authRemoteHost;


    @Override
    public AuthInfoVO passwordLogin(PasswordLoginAuthDTO dto) throws Exception {
        if (dto instanceof PasswordCaptchaLoginAuthDTO) {
            PasswordCaptchaLoginAuthDTO captchaDTO = (PasswordCaptchaLoginAuthDTO) dto;
            String captchaCache = authCache.getCaptchaAndDelete(captchaDTO.getCaptcha().toLowerCase());
            if (captchaCache == null) {
                throw new UserActionException("验证码已过期，请重新生成验证码");
            }
        }
        System.out.println("password:" + dto.getPassword());
        String password;
        try {
            password = Sm2Tool.decrypt(authConfig.getPasswordPrivateKey(), dto.getPassword());
        } catch (Exception e) {
            log.error("SM2 decrypt password error for username: [{}]", dto.getUsername(), e);
            throw new UserActionException("密码需要按规则进行加密");
        }
        LoginErrorDTO loginError = authCache.getLoginError(dto.getUsername());
        if (loginError != null) {
            checkMaxLoginError(loginError, dto.getUsername(), LoginMissTypeEnum.By_PASSWORD);
        }
        LambdaQueryWrapper<UserDO> userQuery = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, dto.getUsername());
        UserDO user = userDAO.selectOne(userQuery);
        boolean isPasswordMatched = false;
        SysUserDO userExtra = null;
        if (user != null) {
            String encryptedPassword = user.getPassword();
            boolean isSM2Matched = passwordEncoder.matches(password, encryptedPassword);
            if (isSM2Matched) {
                isPasswordMatched = true;
            } else {
                log.error("Password mismatch for user in first table, trying second table, username: {}", dto.getUsername());
            }
        }
        RemoteVO vo=null;
        if (!isPasswordMatched) {
//            LambdaQueryWrapper<SysUserDO> userExtraQuery = Wrappers.lambdaQuery(SysUserDO.class)
//                    .eq(SysUserDO::getUsercode, dto.getUsername());
            userExtra = sysUserDAO.selectByName(dto.getUsername());
            if (userExtra == null) {
                log.error("User not found for login in both tables, username: {}", dto.getUsername());
                processLoginError(dto.getUsername(), LoginMissTypeEnum.By_PASSWORD);
                throw new UserActionException("用户名或密码错误");
            } else {
                String inputPassword = Sm2Tool.decrypt(authConfig.getPasswordPrivateKey(), dto.getPassword());
//                Md5Tool.encode(userExtra.getUsercode()+inputPassword).equals(userExtra.getPassword())
//                token = acquireRemoteToken(userExtra.getUsercode(), inputPassword);
//                 vo = acquireRemoteToken(userExtra.getUsercode(), inputPassword);
                user = new UserDO();
                user.setUsername(userExtra.getUsercode());
                user.setRealname(userExtra.getUsername());
                user.setPassword(userExtra.getPassword());
                user.setStatus(0);
                user.setId(String.valueOf(userExtra.getUserId()));
            }
        }
        authCache.delLoginError(dto.getUsername());
        checkUserStatus(user);
        AuthInfoVO authInfoVO = buildAuthInfoVO(user);
        if (null!=vo){
            authInfoVO.setRemoteToken(vo.getRemoteToken());
            authInfoVO.setAuthList(vo.getAuthList());
        }
        return authInfoVO;
    }

    @Override
    public AuthInfoVO phoneLogin(PhoneLoginDTO loginDTO) throws Exception {
        String codeCache = authCache.getPhoneCaptcha(loginDTO.getPhone());
        if (Strings.isBlank(codeCache)) {
            throw new UserActionException("验证码已过期或未发送验证码，请重新发送验证码");
        }
        authCache.delPhoneCaptcha(loginDTO.getPhone());
        LambdaQueryWrapper<UserDO> query = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getPhone,
                loginDTO.getPhone());
        UserDO user = userDAO.selectOne(query);
        if (user == null) {
            throw new UserActionException("当前系统该手机号码不存在，请重新输入");
        }

        LoginErrorDTO logineError = authCache.getLoginError(loginDTO.getPhone());
        if (logineError != null) {
            checkMaxLoginError(logineError, loginDTO.getPhone(), LoginMissTypeEnum.BY_PHONE);
        }

        if (!codeCache.equals(loginDTO.getCaptcha())) {
            processLoginError(loginDTO.getPhone(), LoginMissTypeEnum.BY_PHONE);
        }
        authCache.delLoginError(loginDTO.getPhone());
        checkUserStatus(user);
        return buildAuthInfoVO(user);
    }

    @Override
    public AuthInfoVO secretKeyLogin(String secretKey) throws Exception {
        String userId = authCache.getTokenValue(secretKey, String.class);
        UserDO userDO = userDAO.selectById(userId);
        SysUserDO sysUserDO = sysUserDAO.selectById(userId);
        if (Objects.isNull(userDO) && Objects.isNull(sysUserDO)) {
            throw new UserActionException("用户不存在");
        }
        if (!Objects.isNull(sysUserDO)) {
            userDO = new UserDO();
            userDO.setUsername(sysUserDO.getUsername());
            userDO.setPassword(sysUserDO.getPassword());
            userDO.setId(String.valueOf(sysUserDO.getUserId()));
            userDO.setStatus(0);
        }
        checkUserStatus(userDO);
//        logout(userId);
        return buildAuthInfoVO(userDO);
    }

    @Override
    public Boolean verification(String secretKey) {
        Long ttl = authCache.getTokenTTL(secretKey);
        if (ttl == null || ttl <= 0) {
            return false;
        }
        long expireTime = authConfig.getTokenExpireTime();
        if (ttl <= (expireTime / 2)) {
            log.warn("Token [{}] 接近过期，剩余时间 [{}] 秒", secretKey, ttl);
        }
        return true;
    }

    public void checkMaxLoginError(LoginErrorDTO logineError, String key, LoginMissTypeEnum type) throws Exception {
        Integer currentErrorNum = logineError.getErrorNum() + 1;
        if (currentErrorNum < authConfig.getMaxLoginErrorNum()) {
            return;
        }
        Long ttl = authCache.getLoginErrorTTL(key);
        String time = new BetweenFormatter(ttl * 1000, BetweenFormatter.Level.SECOND).format();
        if (type == LoginMissTypeEnum.By_PASSWORD) {
            throw new DataNotFoundException("账号或密码输入错误，请" + time + "之后重试");
        }
        throw new DataNotFoundException("验证码输入错误，请" + time + "之后重试");
    }

    private void processLoginError(String key, LoginMissTypeEnum type) throws Exception {
        LoginErrorDTO loginError = authCache.getLoginError(key);
        if (loginError == null) {
            // 第一次登录错误，设置时间与次数
            authCache.setLoginError(key, new LoginErrorDTO(1, new Date()), authConfig.getMaxLoginErrorRetryTime());
            throwLoginError(type, 1, authConfig.getMaxLoginErrorNum());
        }
        // 当前登录错误次数
        Integer currentErrorNum = loginError.getErrorNum() + 1;
        loginError.setErrorNum(currentErrorNum);
        if (currentErrorNum >= authConfig.getMaxLoginErrorNum()) { // 达到最大登录次数
            // 重新设置过期时间，用于控制可再次登录时间，过期了表示可以再次登录
            authCache.setLoginError(key, loginError, authConfig.getMaxLoginErrorRetryTime());
        } else {
            authCache.setLoginError(key, loginError, authCache.getLoginErrorTTL(key));
        }
        throwLoginError(type, currentErrorNum, authConfig.getMaxLoginErrorNum());
    }

    private void throwLoginError(LoginMissTypeEnum type, long currentErrorNum, long maxErrorNum) {
        String errorMsg = "";
        if ((maxErrorNum - currentErrorNum) / (double) maxErrorNum < 0.6) {
            errorMsg = "，还剩" + (maxErrorNum - currentErrorNum) + "次登录机会";
        }
        if (type == LoginMissTypeEnum.By_PASSWORD) {
            throw new DataNotFoundException("账号或密码错误" + errorMsg);
        }
        throw new DataNotFoundException("验证码输入错误" + errorMsg);
    }

    private void checkUserStatus(UserDO user) {
        if (user == null) {
            log.error("User object is null in checkUserStatus");
            throw new NullPointerException("User object is null");
        }


        if (user.getStatus() == null) {
            log.info("auth login, user status is null, username: {}", user.getUsername());
            throw new UserActionException(SystemExceptionStatus.ACCOUNT_ANOMALY);
        }
        UserStatusEnum accountStatus = EnumConverter.conver(UserStatusEnum.values(), user.getStatus());
        if (accountStatus == null) {
            log.info("auth login, user status conver result null, username: {}, status: {}", user.getUsername(),
                    user.getStatus());
            throw new UserActionException(SystemExceptionStatus.ACCOUNT_ANOMALY);
        }
        if (UserStatusEnum.NORMAL != accountStatus) {
            log.info("auth login, user status conver result is not {}, username: {}, status: {}",
                    UserStatusEnum.NORMAL.getCode(), user.getUsername(), user.getStatus());
            throw new UserActionException(SystemExceptionStatus.ACCOUNT_ANOMALY);
        }
    }

    @Override
    public String generateCaptchaBase64() {
        try {
            String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";
            String code = RandomUtil.randomString(BASE_CHECK_CODES, authConfig.getCaptchaLength());
            String lowerCaseCode = code.toLowerCase();
            authCache.setCaptcha(lowerCaseCode, authConfig.getCaptchaExpireTime());
            log.debug("generate captcha: {}", lowerCaseCode);
            return LoginCaptchaImageTool.generate(code);
        } catch (Exception e) {
            log.error("generate captcha error: ", e);
            throw new ServeException("验证码生成出现异常");
        }
    }


    @Override
    public void logout(String token) {
        String id = JwtTool.getId(token);
        if (StrUtil.isEmpty(id)) {
            throw new UserActionException("非法的Token值");
        }
        authCache.delToken(id);
        //删除大数据token
        authCache.delBigDataToken(id);
    }

    @Override
    public LoginInfoVO authToken(String token) {
        if (StrUtil.isEmpty(token)) {
            throw new UserActionException("Token缺失");
        }
        String userId = JwtTool.getUserId(token);
        if(StrUtil.isNotEmpty(userId)
                && "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiIxIiwianRpIjoiMTczNzA4MDM4MTc5Ny0xLWl5In0.GfSfcT93Vhte9Wnz8sIcWSH8HfEAWwBnb0zj-MI4srU".equals(token)){
        }else {
            if (StrUtil.isEmpty(userId)) {
                throw new UserActionException("非法的Token值");
            }
            String tokenId = JwtTool.getId(token);
            Long tokenTTL = authCache.getTokenTTL(JwtTool.getId(token));
            if (tokenTTL == null) {
                throw new AuthenticationFailureException("登录已过期，请重新登录");
            }
            if (tokenTTL != -1) {
                long expireTime = authConfig.getTokenExpireTime();
                if (tokenTTL <= (expireTime / 2)) {
                    if (!authCache.refreshTokenExpireTime(tokenId, authConfig.getTokenExpireTime())) {
                        log.error("Refresh token expire time result is false, token id [{}]", tokenId);
                    }
                }
            }
        }

        UserDO user = userDAO.selectById(userId);
        SysUserDO aDo = sysUserDAO.selectById(userId);
        if (user == null && aDo == null) {
            throw new DataNotFoundException("账号不存在");
        }
        if (user == null && aDo != null) {
            user = new UserDO();
            user.setUsername(aDo.getUsername());
            user.setRealname(aDo.getUsercode());
            user.setPassword(aDo.getPassword());
            user.setStatus(0);
            user.setId(String.valueOf(aDo.getUserId()));
        }
        checkUserStatus(user);
        LoginInfoVO loginInfo = new LoginInfoVO();
        loginInfo.setUser(UserConverter.INSTANCE.toUserLoginInfoVO(user));
        loginInfo.setDept(DeptConverter.INSTANCE.toLoginUserDeptVO(deptDAO.selectById(user.getDeptId())));
        loginInfo.setDataScopeUserIds(userService.getDataSopeUserIds(userId));
        // 当前用户所在部门为管理员
        if (ObjectUtil.equal(UserIdentityEnum.ADMIN.getCode(), user.getUserIdentity())) {
            Set<String> deptIds = deptDAO.findChildrenDeptIds(loginInfo.getDept().getTreeCode(), "");
            loginInfo.setDataScopeDeptIds(deptIds);
        } else {
            HashSet<String> deptIds = new HashSet<String>();
            deptIds.add(user.getDeptId());
            loginInfo.setDataScopeDeptIds(deptIds);
        }
        return loginInfo;
    }

    private AuthInfoVO buildAuthInfoVO(UserDO user) {
        List<RoleVO> roleVOs = sysUserDAO.selectRoleByName(user.getUsername());

        AuthInfoVO loginInfo = new AuthInfoVO();
        LoginUserVO userLoginInfoVO = UserConverter.INSTANCE.toUserLoginInfoVO(user);
        userLoginInfoVO.setRoleVOS(roleVOs);
        loginInfo.setUser(userLoginInfoVO);
        String tokenId = JwtTool.generateId(user.getId());
        String token = JwtTool.generateToken(user.getId(), tokenId);
        loginInfo.setToken(token);
        authCache.setToken(tokenId, token, authConfig.getTokenExpireTime());
        loginInfo.setDept(DeptConverter.INSTANCE.toDeptInfoVO(deptDAO.selectById(user.getDeptId())));
        if (UserTypeEnum.SUPER_ADMIN.getCode().equals(user.getUserType())) {
            loginInfo.setPagePermissionTree(pagePermissionService.findTree(null));
        } else {
            loginInfo.setPagePermissionTree(userService.byUserIdFindPagePermissionTree(user.getId()));
        }
        try {
            String bigDataToken = acquireBigDataToken(tokenId);
            loginInfo.setBigDataToken(bigDataToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loginInfo;
    }

    @Override
    public void sendPhoneCode(String phone) {
        try {
            LambdaQueryWrapper<UserDO> query = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getPhone, phone);
            UserDO user = userDAO.selectOne(query);
            if (user == null) {
                throw new UserActionException("当前系统该手机号码不存在，请重新输入");
            }
            String code = neteaseMessageService.sendCodeMessage(phone);
            boolean result = authCache.setPhoneCaptcha(phone, code, neteasePhoneCodeMessageConfig.getExpireTime());
            if (!result) {
                throw new ServeException("缓存验证码失败");
            }
        } catch (AbstractCommonException e) {
            throw e;
        } catch (Exception e) {
            throw new UserActionException("发送短信失败");
        }

    }

    public String acquireBigDataToken(String token) {
        HttpRequest request = HttpUtil
                .createPost(authBigDataHost + "/system/auth/login/password");
        request.timeout(10000);
        request.body("{\"username\": \"" + authBigDataName + "\",\"password\": \"" + authBigDataPwd + "\"}");
        try (HttpResponse response = request.execute()) {
            if (response.getStatus() != 200) {
                throw new UserActionException("获取大数据Token失败，响应状态码：" + response.getStatus());
            }
            String dataJson = response.body();
            if (StrUtil.isBlank(dataJson)) {
                throw new UserActionException("大数据Token信息为空");
            }

            JSONObject jsonObject = JSON.parseObject(dataJson);
            int code = (int) jsonObject.get("code");
            if (code != 5000) {
                throw new UserActionException("获取大数据Token异常" + jsonObject.get("message"));
            }
            JSONObject jsonObject1 = (JSONObject) jsonObject.get("data");
            String bigDataToken = (String) jsonObject1.get("token");
            // 一个持有大数据token，一个记录刷新时间
            authCache.setToken(token + "_big_data_token", bigDataToken, authBigDataTime);
            return bigDataToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new UserActionException("获取大数据Token异常");
        }
    }

    public RemoteVO acquireRemoteToken(String username, String password) {
        //http://10.34.186.150/rsvrApi/web/login/userLogin
        String key = "645276589226429";
        try {
            username = DesTool.encryptDes(username, key);
            password = DesTool.encryptDes(password, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpRequest request = HttpUtil
                .createPost(authRemoteHost + "/web/login/userLogin");
        request.timeout(10000);
        request.body("{\"userCode\": \"" + username + "\",\"password\": \"" + password + "\"}");

        try (HttpResponse response = request.execute()) {
            if (response.getStatus() != 200) {
                throw new UserActionException("获取远程Token失败，响应状态码: " + response.getStatus());
            }
            String dataJson = response.body();
            if (StrUtil.isBlank(dataJson)) {
                throw new UserActionException("远程Token信息为空");
            }
            System.out.println(dataJson);
            JSONObject jsonObject = JSON.parseObject(dataJson);
            String codeStr = jsonObject.getString("code");
            if (codeStr != null && Integer.parseInt(codeStr) != 200) {
                throw new UserActionException("获取远程Token异常" + jsonObject.get("msg"));
            }
            JSONObject jsonObject1 = (JSONObject) jsonObject.get("data");
            System.out.println(jsonObject1.toString());
            // 获取 token
            String remoteToken = (String) jsonObject1.get("token");
            JSONArray authList = jsonObject1.getJSONArray("authList");// 获取 JSONArray
            List<String> list = authList.toJavaList(String.class);
            RemoteVO vo = new RemoteVO();
            vo.setRemoteToken(remoteToken);
            vo.setAuthList(list);


            return vo;
        } catch (Exception e) {
            return null;
//            e.printStackTrace();
//            throw new UserActionException("获取远程Token异常");
        }
    }


    public static String encryptDes(String message, String key) throws Exception {
        // 1. 将密钥转换为字节数组，并生成DES密钥
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        // 2. 使用ECB模式和PKCS5Padding进行加密
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // 3. 加密消息
        byte[] encryptedBytes = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));

        // 4. 将加密结果转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : encryptedBytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }

    public static String decryptDes(String encryptedMessage, String key) throws Exception {
        // 将密钥转换为字节数组并生成DES密钥
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        // 初始化解密模式
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // 将十六进制的加密消息转换为字节数组
        byte[] encryptedBytes = hexStringToByteArray(encryptedMessage);

        // 解密消息
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }


    public static void main(String[] args) {
        try {
            String message = "QvAwd@50581563";
            String key = "6452765859226429"; // 密钥必须为8字节
            String encryptedMessage = encryptDes(message, key);
            System.out.println("Encrypted Message (Hex): " + encryptedMessage);
            String decryptedMessage = decryptDes(encryptedMessage, key);
            System.out.println("Decrypted Message: " + decryptedMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}





